package com.dhcy.mqtt.config;



import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.dhcy.mqtt.dao.*;
import com.dhcy.mqtt.exception.GlobalException;
import com.dhcy.mqtt.model.SysRoleResource;
import com.dhcy.mqtt.model.SysUser;
import com.dhcy.mqtt.model.SysUserRole;
import com.dhcy.mqtt.util.AppResultData;
import com.dhcy.mqtt.util.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;


    @Autowired
    SysResourceMapper sysResourceMapper;
    @Autowired
    SysRoleResourceMapper sysRoleResourceMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;




    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        String username = (String) principals.getPrimaryPrincipal();
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        SysUser sysUser = sysUserMapper.selectByMap(map).get(0);
        map = new HashMap<>();
        map.put("user_id", sysUser.getId());
        SysUserRole sysUserRole = sysUserRoleMapper.selectByMap(map).get(0);
        map = new HashMap<>();
        map.put("role_id", sysUserRole.getRoleId());
        List<SysRoleResource> sysRoleResourceList = sysRoleResourceMapper.selectByMap(map);
        Set<String> preList = new HashSet<>();
        for (SysRoleResource sysRoleResource : sysRoleResourceList) {
            preList.add(sysRoleResource.getResourceCode());
        }

        authorizationInfo.setStringPermissions(preList);
        return authorizationInfo;
    }

    @Autowired
    RedisDao redisDao;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken){
//        String token = (String) authenticationToken.getCredentials();
//        String username = JWTUtil.getUsername(token); //从token中获取username
//        Integer userId = JWTUtil.getUserId(token);    //从token中获取userId
////         通过redis查看token是否过期
//        HttpServletRequest request = getHttpServletRequest();
//        String encryptTokenInRedis = redisDao.getValue("Constant.RM_TOKEN_CACHE" + token + StringPool.UNDERSCORE);
//        if (!token.equalsIgnoreCase(encryptTokenInRedis)) {
//            throw new AuthenticationException("token已经过期");
//        }
//        // 如果找不到，说明已经失效
//        if (StringUtils.isBlank(encryptTokenInRedis)) {
//            throw new AuthenticationException("token已经过期");
//        }
//
//        if (StringUtils.isBlank(username)) {
//            throw new AuthenticationException("token校验不通过");
//        }

//        String token = (String) authenticationToken.getCredentials();
        // 解密获得username，用于和数据库进行对比
//        String username = JWTUtil.getUsername(token);
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        String username = userToken.getUsername();
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        List<SysUser> sysUserList = sysUserMapper.selectByMap(map);
        if (sysUserList.size() == 0) {
            throw new GlobalException(AppResultData.errorMessage("用户名不存在"));
           // return  null;
        }
        SysUser sysUser = sysUserList.get(0);
        if(sysUser.getStatus()==1){
            throw new GlobalException(AppResultData.errorMessage("账号已停用"));
        }
        return new SimpleAuthenticationInfo(sysUser.getUsername(), sysUser.getPassword(), this.getClass().getName());
    }

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }
}
